<template>
  <div class="container">
    <el-card>
      <div class="set-container">
        <div  class="select-container">
          <el-form ref="selectForm" :inline="true" :model="selectForm" class="select-form">
            <el-form-item prop="username" label="用户姓名:">
              <el-input v-model="selectForm.username" placeholder="请输入姓名" class="select-input-1" size="medium"></el-input>
            </el-form-item>
            <el-form-item prop="date" label="注册时间:">
              <el-date-picker
                  size="medium"
                  v-model="selectForm.date"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item prop="authority" label="用户权限">
              <el-select class="select-input-2" v-model="selectForm.authority" placeholder="请选择" size="medium">
                <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button-group>
                <el-button type="primary" size="medium" @click="submitSelect(1)">查询</el-button>
                <el-button type="info" size="medium" @click="resetSelect">重置</el-button>
              </el-button-group>
            </el-form-item>
          </el-form>
        </div>
        <div class="button-container">
          <el-button type="success" size="medium" @click="addUser">新增用户</el-button>
          <el-button type="danger" size="medium" @click="showDialog">批量操作</el-button>
          <el-button type="info" size="medium">导出表格</el-button>
        </div>
      </div>
      <el-divider><h3 style="text-align: center">用户信息表格</h3></el-divider>
      <div class="table-container">
        <el-table
            v-if="tableData.length > 0"
            :data="tableData"
            @selection-change="handleSelectionChange"
            border
            stripe
            style="width: 100%"
        >
          <el-table-column
              type="selection"
              width="45">
          </el-table-column>
          <el-table-column prop="avatarUrl" label="头像" width="55">
            <template slot-scope="scope">
              <div class="avatar-center">
                <el-avatar
                    shape="square"
                    :size="35"
                    :src="scope.row.avatarUrl"
                >
                  <img
                      src="https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png"
                      alt="头像"
                  />
                </el-avatar>
              </div>
            </template>
          </el-table-column>
          <el-table-column
              prop="username"
              label="用户名"
              width="150">
          </el-table-column>
          <el-table-column
              prop="nickname"
              label="昵称"
              width="150">
          </el-table-column>
          <el-table-column
              prop="name"
              label="姓名"
              width="120">
          </el-table-column>
          <el-table-column
              prop="gender"
              label="性别"
              width="50">
          </el-table-column>
          <el-table-column
              prop="phone"
              label="手机号"
              width="120">
          </el-table-column>
          <el-table-column
              prop="mail"
              label="邮箱"
              width="200">
          </el-table-column>
          <el-table-column prop="createTime" label="注册时间">
            <template slot-scope="scope">
              <i class="el-icon-time"></i>
              {{ formatCreateTime(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="authority" label="权限" width="100">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.authority === 1" effect="dark">普通用户</el-tag>
              <el-tag v-else-if="scope.row.authority === 0" type="warning" effect="dark">注销用户</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="180">
            <template slot-scope="scope">
              <el-button-group>
                <el-button type="primary" icon="el-icon-edit" size="mini" plain @click="openEditUserDialog(scope.row.id)" >编辑</el-button>
                <el-button  v-if="scope.row.authority===1" type="warning" icon="el-icon-user" size="mini" plain @click="logout(scope.row.id,0)" >注销</el-button>
                <el-button  v-else icon="el-icon-user" size="mini" plain @click="logout(scope.row.id,1)">激活</el-button>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>
        <el-empty :image-size=350  v-else description="暂无数据"></el-empty>
      </div>
      <el-divider></el-divider>
      <div class="page">
        <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="selectForm.page"
            :page-sizes="[5, 7, 10, 20, 50]"
            :page-size="selectForm.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
      </div>
    </el-card>

    <el-dialog
        title="新增用户"
        :visible.sync="AddUserDialog"
        width="30%"
        top="3vh">

      <el-form
          :model="addUserForm"
          :rules="addUserRules"
          ref="addUserForm"
          label-width="100px"
          class="addUserForm"
      >
        <el-form-item prop="avatarUrl" label="头像">
          <el-upload
              class="avatar-uploader"
              action=""
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :http-request="uploadAvatar"
          >
            <img v-if="addUserForm.avatarUrl" :src="addUserForm.avatarUrl" class="avatar" alt="头像">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item prop="username" label="用户名">
          <el-input
              v-model="addUserForm.username"
              maxlength="16"
              show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item prop="nickname" label="昵称">
          <el-input
            v-model="addUserForm.nickname"
            maxlength="10"
            show-word-limit>
          </el-input>
        </el-form-item>
        <el-form-item prop="name" label="姓名">
          <el-input
              v-model="addUserForm.name"
              maxlength="16"
              show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item prop="sex" label="性别">
          <el-radio v-model="addUserForm.gender" label="男">男</el-radio>
          <el-radio v-model="addUserForm.gender" label="女">女</el-radio>
        </el-form-item>
        <el-form-item prop="phone" label="手机号">
          <el-input
              v-model="addUserForm.phone"
              minlength="11"
              maxlength="11"
              show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item prop="mail" label="邮箱">
          <el-input
              v-model="addUserForm.mail"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
              type="primary"
              @click="submitAddUserForm(addUserForm)"
          >提交</el-button
          >
          <el-button @click="resetAddUserForm"
          >重置</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog
        title="编辑用户"
        :visible.sync="editUserDialog"
        width="30%"
        top="3vh">
      <el-form  :model="editUserForm"
                :rules="addUserRules"
                ref="editUserForm"
                label-width="100px"
                class="editUserForm">
        <el-form-item prop="avatarUrl" label="头像">
          <el-upload
              class="avatar-uploader"
              action=""
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :http-request="uploadEditAvatar"
          >
            <img v-if="editUserForm.avatarUrl" :src="editUserForm.avatarUrl" class="avatar" alt="头像">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item prop="username" label="用户名">
          <el-input
              v-model="editUserForm.username"
              maxlength="16"
              show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item prop="nickname" label="昵称">
          <el-input
              v-model="editUserForm.nickname"
              maxlength="10"
              show-word-limit>
          </el-input>
        </el-form-item>
        <el-form-item prop="authority" label="权限">
          <el-select v-model="editUserForm.authority" placeholder="请选择">
            <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="name" label="姓名">
          <el-input
              v-model="editUserForm.name"
              maxlength="16"
              show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item prop="gender" label="性别">
          <el-radio v-model="editUserForm.gender" label="男">男</el-radio>
          <el-radio v-model="editUserForm.gender" label="女">女</el-radio>
        </el-form-item>
        <el-form-item prop="phone" label="手机号">
          <el-input
              v-model="editUserForm.phone"
              minlength="11"
              maxlength="11"
          ></el-input>
        </el-form-item>
        <el-form-item prop="mail" label="邮箱">
          <el-input
              v-model="editUserForm.mail"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
              type="primary"
              @click="submitEditUserForm(editUserForm)"
          >提交</el-button
          >
          <el-button @click="resetEditUserForm"
          >重置</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog
        title="批量操作"
        :visible.sync="dialog"
        width="40%"
        center>
      <h3 style="color: red;text-align: center">这可能会给数据造成无法恢复的后果，请确认后选择所需操作！</h3>
       <span slot="footer" class="dialog-footer">
          <el-button  @click="activeUser">批量激活</el-button>
    <el-button type="warning" @click="logoutUser">批量注销</el-button>
    <el-button type="danger">批量删除</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from "@/api/axios";

export default {
  data(){
    return {
      selectForm:{
        username:"",
        date:"",
        pageSize:7,
        page:1,
        authority:"",
      },
      total:0,
      tableData:[],

      AddUserDialog:false,
      addUserForm:{
        avatarUrl:"",
        username:"",
        nickname:"",
        name:"",
        gender:"男",
        phone:"",
        mail:"",
      },

      editUserDialog:false,
      editUserForm:{
        id:"",
        avatarUrl:"",
        username:"",
        nickname:"",
        name:"",
        gender:"男",
        phone:"",
        mail:"",
        authority:1,
      },

      dialog:false,
      ids:[],

      options: [
        {
        value: 0,
        label: '注销用户'
      }, {
        value: 1,
        label: '普通用户'
      }
      ],

      addUserRules:{
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 6,
            max: 16,
            message: "长度在 6 到 16 个字符",
            trigger: "blur",
          },
          { validator: this.noSpacesValidator, trigger: "blur" }, // 添加自定义验证器
        ],
        nickname: [
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
          { validator: this.noSpacesValidator, trigger: "blur" }, // 添加自定义验证器
        ],
        name: [
          {
            min: 2,
            max: 16,
            message: "长度在 2 到 16 个字符",
            trigger: "blur",
          },
          { validator: this.noSpacesValidator, trigger: "blur" }, // 添加自定义验证器
        ],
        phone: [
            // 添加正则表达式 pattern: /^1[3|5|7|8|9]\d{9}$/，验证手机号是否正确
            { pattern: /^1[3|5|7|8|9]\d{9}$/, message: '请输入正确的号码格式', trigger: 'blur' }
        ],
        mail: [
            { pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+$/
              , message: '请输入正确的邮箱格式', trigger: 'blur' }
            ],
      }
    }
  },

  mounted() {
    this.submitSelect();
  },

  methods:{
    /**
     * 表格数据查询函数
     */
    submitSelect(flag) {
      this.$refs.selectForm.validate((valid) => {
        if (flag===1) {
          this.selectForm.page = 1;// 重新查询时，将页码置为第一页
        }
        if (valid) {
          const formData = {
            page: this.selectForm.page,
            pageSize: this.selectForm.pageSize,
            name: this.selectForm.username,
            begin: this.formatDate(this.selectForm.date[0]),
            end: this.formatDate(this.selectForm.date[1]),
            authority: this.selectForm.authority,
          };

          axios.post("/admin/user/list", formData).then(response => {
            if (response.data.code === 0) {
              this.$message.error(response.data.msg);
            }else {
              this.tableData = response.data.data.records;
              this.total = response.data.data.total;
            }
          }).catch(error=> {
            // 处理请求错误
            console.log(error);
          });
        }else{
          console.log("error submit!");
          return false;
        }
      })
    },

    /**
     * 日期处理函数
     * @param date
     * @returns {null|string}
     */
    formatDate(date) {
      if (date instanceof Date) {
        // 返回格式化后的日期时间字符串（ISO 8601 UTC格式，不包含毫秒）
        return (
            date.toISOString().split("T")[0] +
            "T" +
            date.toISOString().split("T")[1].split(".")[0]
        );
      } else {
        // 如果日期为空或者不是Date对象，返回null或空字符串，或者根据你的需求返回其他默认值
        return null; // 或者 ""，取决于后端如何处理这种情况
      }
    },


    /**
     * 两个分页选项函数
     * @param val
     */
    handleSizeChange(val) {
      this.selectForm.pageSize = val;
      this.submitSelect();
    },
    handleCurrentChange(val) {
      this.selectForm.page=val;
      this.submitSelect();
    },


    /**
     * 查询表单重置函数
     */
    resetSelect() {
      this.$refs.selectForm.resetFields(this.selectForm);
      this.$message.info("重置成功");
    },

    /**
     * 给返回的时间格式化函数
     * @param {Array} createTime - 包含年、月、日、时、分、秒的数组
     * @returns {string}
     */
    formatCreateTime(createTime) {
      const [year, month, day, hour, minute = '00', second = '00'] = createTime;
      return `${year}-${this.padZero(month)}-${this.padZero(day)} ${this.padZero(hour)}:${this.padZero(minute)}:${this.padZero(second)}`;
    },

    /**
     * 将数字补零
     * @param {number|string} num
     * @returns {string}
     */
    padZero(num) {
      return num.toString().padStart(2, '0');
    },

    /**
     * 新增用户
     */
    addUser(){
      this.AddUserDialog = true;
    },

    /*头像上传方法*/
    uploadAvatar(file) {
      axios.post("/admin/common/upload", file,{headers:{'Content-Type': 'multipart/form-data',}}).then((response) => {
        if(response.data.code===0){
          this.$message.error(response.data.msg);
        }else {
          this.addUserForm.avatarUrl=response.data.data;
          this.$message.success("上传成功");
        }
      }).catch((error) => {
        console.log(error);
      })
    },
    uploadEditAvatar(file) {
      axios.post("/admin/common/upload", file,{headers:{'Content-Type': 'multipart/form-data',}}).then((response) => {
        if(response.data.code===0){
          this.$message.error(response.data.msg);
        }else {
          this.editUserForm.avatarUrl=response.data.data;
          this.$message.success("上传成功");
        }
      }).catch((error) => {
        console.log(error);
      })
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },

    /**
     * 重置添加表单
     */
    resetAddUserForm(){
      this.$refs.addUserForm.resetFields(this.addUserForm);
    },

    /**
     * 添加用户
     */
    submitAddUserForm(){
      this.$refs["addUserForm"].validate((valid) => {
        if (valid) {
          axios.post("/admin/user/add", this.addUserForm).then(response => {
            if (response.data.code === 0) {
              this.$message.error(response.data.msg);
            }else {
              this.$message.success("添加成功");
              this.AddUserDialog = false;
             this.submitSelect()//刷新页面
            }
          }).catch(error=> {
            // 处理请求错误
            console.log(error);
          });
        }else{
          console.log("error submit!");
          return false;
        }
      })
    },

    /**
     * 空格校验
     * @param rule
     * @param value
     * @param callback
     */
    noSpacesValidator(rule, value, callback) {
      if (value && typeof value === "string" && value.includes(" ")) {
        callback(new Error("不能包含空格"));
      } else {
        callback();
      }
    },

    /**
     * 编辑用户
     * @param id
     */
    openEditUserDialog(id) {
      this.editUserDialog = true;
      this.getUserById(id);
    },

    /**
     * 获取用户信息
     */
    getUserById(id) {
      axios.get("/admin/user/" + id).then(response => {
        if (response.data.code === 0) {
          this.$message.error(response.data.msg);
        } else {
          this.editUserForm = response.data.data;
        }
      }).catch(error => {
        console.log(error);
      })
    },

    /**
     * 重置编辑表单
     */
    resetEditUserForm(){
      this.getUserById(this.editUserForm.id);
    },

    /**
     * 提交编辑用户信息
     */
    submitEditUserForm(){
      this.$refs["editUserForm"].validate((valid) => {
        if (valid) {
          axios.put("/admin/user/update", this.editUserForm).then(response => {
            if (response.data.code === 0) {
              this.$message.error(response.data.msg);
            }else {
              this.$message.success("修改成功");
              this.editUserDialog = false;
             this.submitSelect();//刷新页面
            }
          }).catch(error=> {
            console.log(error);
          })
        }else {
          console.log("error submit!");
          return false;
        }
      })
    },

    /**
     * 注销/激活
     */
    logout(id,auth) {
      axios.put("/admin/user/logout/" + id + "/" + auth).then(response => {
        if (response.data.code === 0) {
          this.$message.error(response.data.msg);
        }else {
          this.submitSelect();//刷新页面
        }
      }).catch(error => {
        console.log(error);
      })
    },

    /**
     * 批量操作提示框
     */
    showDialog(){
      this.dialog = true;
    },

    /**
     * 选择框
     */
    handleSelectionChange(val){
      // 创建一个新的数组来存储 id
      const ids = [];

      // 遍历 val 数组,并将每个对象的 id 属性值添加到 ids 数组中
      val.forEach(item => {
        ids.push(item.id);
      });

      this.ids = ids;
    },

    /**
     * 批量注销
     */
    logoutUser(){
      this.dialog=false;
      if(this.ids.length===0){
        this.$message.error("未选择要注销的用户");
        return;
      }
      axios.put("/admin/user/logouts", this.ids).then(response => {
        if (response.data.code === 0) {
          this.$message.error(response.data.msg);
        }else {
          this.$message.success("注销成功");
          this.submitSelect();
        }
      }).catch(error => {
        console.log(error);
      })
    },

    /**
     * 批量激活
     */
    activeUser(){

    }

    /**
     * 批量删除
     */
  },
}
</script>

<style scoped>
/*收缩选择框所占空间*/
.select-input-1{
  width: 100px;
}

.select-input-2{
  width: 120px;
}

/*表格最小高度*/
.table-container{
  min-height: 60vh;
}

/*表格顶部设置栏*/
.set-container{
  display: flex;
}

.button-container{
  margin-left: auto; /* 将按钮容器向右对齐 */
}

/*分页*/
.page{
  margin-top: 20px;
}
</style>